package com.ruoyi.commodity.service.impl;

import com.alibaba.nacos.shaded.com.google.protobuf.ServiceException;
import com.ruoyi.commodity.domain.CommodityCategory;
import com.ruoyi.commodity.domain.vo.CommodityTreeSelect;
import com.ruoyi.commodity.mapper.CommodityCategoryMapper;
import com.ruoyi.commodity.service.ICommodityCategoryService;
import com.ruoyi.common.core.constant.CommodityCategoryConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @BelongsProject: group-4
 * @BelongsPackage: com.ruoyi.commodity.service.impl
 * @Author: Steven
 * @CreateTime: 2023-07-12  14:53
 * @Version: 1.0
 */
@Service
public class CommodityCategoryServiceImpl implements ICommodityCategoryService {
    @Autowired
    private CommodityCategoryMapper commodityCategoryMapper;

    /**
     * @description:查询分类管理数据
     * @author: Steven
     * @date: 2023/7/12 0012 15:13
     * @param: [commodityCategory]
     * @return: java.util.List<com.ruoyi.commodity.domain.CommodityCategory>
     **/
    @Override
    public List<CommodityCategory> selectCommodityCategoryList(CommodityCategory commodityCategory) {
        return commodityCategoryMapper.selectCommodityCategoryList(commodityCategory);
    }

    @Override
    public CommodityCategory selectCommodityCategoryById(Long categoryId) {
        return commodityCategoryMapper.selectCommodityCategoryById(categoryId);
    }

    @Override
    public int insertCommodityCategory(CommodityCategory commodityCategory){
        CommodityCategory info = commodityCategoryMapper.selectCommodityCategoryById(commodityCategory.getParentId());
        if(!CommodityCategoryConstants.CATEGORY_NORMAL.equals(info.getStatus()))
        {
            try {
                throw new ServiceException("该分类停用，不允许新增");
            } catch (ServiceException e) {
                e.printStackTrace();
            }
        }
        commodityCategory.setAncestors(info.getAncestors()+","+commodityCategory.getParentId());
        commodityCategory.setType("产品分类");
        return commodityCategoryMapper.insertCommodityCategory(commodityCategory);
    }

    @Override
    public boolean checkCommodityCategoryNameUnique(CommodityCategory commodityCategory) {
        Long categoryId = StringUtils.isNull(commodityCategory.getCategoryId()) ? -1L : commodityCategory.getCategoryId();
        CommodityCategory info = commodityCategoryMapper.checkCategoryNameUnique(commodityCategory.getCategoryName(),commodityCategory.getCategoryId());
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != categoryId.longValue())
        {
            return CommodityCategoryConstants.NOT_UNIQUE;
        }
        return CommodityCategoryConstants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenCategoryById(Long categoryId) {
        return commodityCategoryMapper.selectNormalChildrenCategoryById(categoryId);
    }


    @Override
    public int updateCommodityCategory(CommodityCategory commodityCategory) {
        CommodityCategory newParentCategory = commodityCategoryMapper.selectCommodityCategoryById(commodityCategory.getParentId());
        CommodityCategory oldCategory = commodityCategoryMapper.selectCommodityCategoryById(commodityCategory.getCategoryId());
        if(StringUtils.isNotNull(newParentCategory)&&StringUtils.isNotNull(oldCategory)){
            String newAncestors = newParentCategory.getAncestors()+","+newParentCategory.getCategoryId();
            String oldAncestors = oldCategory.getAncestors();
            commodityCategory.setAncestors(newAncestors);
            updateCategoryChildren(commodityCategory.getCategoryId(),newAncestors,oldAncestors);
        }
        int result = commodityCategoryMapper.updateCommodityCategory(commodityCategory);
        if(CommodityCategoryConstants.CATEGORY_NORMAL.equals(commodityCategory.getStatus())&&StringUtils.isNotEmpty(commodityCategory.getAncestors())
                && !StringUtils.equals("0",commodityCategory.getAncestors()))
        {
            updateParentCategoryStatusNormal(commodityCategory);
        }
        return result;
    }

    @Override
    public boolean hasChildByCategoryId(Long categoryId) {
        int result = commodityCategoryMapper.hasChildByCategoryId(categoryId);
        return result>0;
    }

    @Override
    public boolean checkCategoryExistCommodity(Long categoryId) {
        int result = commodityCategoryMapper.checkCategoryExistCommodity(categoryId);
        return result>0;
    }

    @Override
    public int deleteCategoryById(Long categoryId) {
        return commodityCategoryMapper.deleteCategoryById(categoryId);
    }


    private void updateParentCategoryStatusNormal(CommodityCategory commodityCategory) {
        String ancestors = commodityCategory.getAncestors();
        Long[] categoryIds = Convert.toLongArray(ancestors);
        commodityCategoryMapper.updateCategoryStatusNormal(categoryIds);
    }

    public void updateCategoryChildren(Long categoryId, String newAncestors, String oldAncestors)
    {
        List<CommodityCategory> children = commodityCategoryMapper.selectChildrenCategoryById(categoryId);
        for (CommodityCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            commodityCategoryMapper.updateCategoryChildren(children);
        }
    }

    @Override
    public List<CommodityTreeSelect> selectCategoryTreeList(CommodityCategory commodityCategory)
    {
        List<CommodityCategory> commodityCategories = commodityCategoryMapper.selectCommodityCategoryList(commodityCategory);
        return buildCategoryTreeSelect(commodityCategories);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @return 下拉树结构列表
     */
    @Override
    public List<CommodityTreeSelect> buildCategoryTreeSelect(List<CommodityCategory> commodityCategories)
    {
        List<CommodityCategory> categoryTrees = buildCategoryTree(commodityCategories);
        return categoryTrees.stream().map(CommodityTreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @return 树结构列表
     */
    @Override
    public List<CommodityCategory> buildCategoryTree(List<CommodityCategory> commodityCategories)
    {
        List<CommodityCategory> returnList = new ArrayList<>();
        List<Long> tempList = commodityCategories.stream().map(CommodityCategory::getCategoryId).collect(Collectors.toList());
        for (CommodityCategory commodityCategory : commodityCategories)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(commodityCategory.getParentId()))
            {
                recursionFn(commodityCategories, commodityCategory);
                returnList.add(commodityCategory);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = commodityCategories;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<CommodityCategory> list, CommodityCategory t)
    {
        // 得到子节点列表
        List<CommodityCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CommodityCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<CommodityCategory> getChildList(List<CommodityCategory> list, CommodityCategory t)
    {
        List<CommodityCategory> tlist = new ArrayList<CommodityCategory>();
        Iterator<CommodityCategory> it = list.iterator();
        while (it.hasNext())
        {
            CommodityCategory n = (CommodityCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<CommodityCategory> list, CommodityCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
